package com.gitee.cui.redis.jedispool;

import lombok.extern.slf4j.Slf4j;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

import java.util.ArrayList;
import java.util.List;

/**
 * Jedis连接池创建器
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/7 20:56
 **/
@Slf4j
public class JedisPoolBuilder {

    /**
     * 最大连接数
     */
    private static final int MAX_TOTAL = 50;

    /**
     * 最小空闲连接数
     */
    private static final int MIN_IDLE = 50;

    private static JedisPool jedisPool;

    static {
        // 构建连接池
        buildPool();

        // 预热连接池中的连接
        hotPool();
    }

    /**
     * 预热连接池中的连接，最小空闲连接数量就可以
     */
    private static void hotPool() {
        long start = System.currentTimeMillis();
        List<Jedis> list = new ArrayList<>();
        Jedis jedis = null;
        for (int i = 0; i < MIN_IDLE; i++) {
            jedis = jedisPool.getResource();
            list.add(jedis);
            jedis.ping();
        }

        for (int i = 0; i < MIN_IDLE; i++) {
            jedis = list.get(i);
            jedis.close();
        }
        long end = System.currentTimeMillis();
        log.info("hotPool毫秒数：{}", end - start);
    }

    /**
     * 构建连接池
     */
    private static void buildPool() {
        if (jedisPool == null ) {
            long start = System.currentTimeMillis();
            JedisPoolConfig config = new JedisPoolConfig();
            config.setMaxTotal(MAX_TOTAL);
            config.setMinIdle(MIN_IDLE);
            config.setMaxWaitMillis(1000 * 10);
            config.setTestOnBorrow(true);

            jedisPool = new JedisPool(config, "localhost", 6379, 10000 );
            long end = System.currentTimeMillis();
            log.info("buildPool毫秒数：{}", end - start);
        }
    }

    /**
     * 对外提供的获取Jedis连接的方法
     * @return Jedis连接
     */
    public static Jedis getJedis() {
        return jedisPool.getResource();
    }
}
